/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mail.web.security;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import mail.web.MailSession;
import org.jboss.seam.security.Authenticator;
import org.jboss.seam.security.BaseAuthenticator;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.UserImpl;

/**
 *
 * @author timoteo
 */
@Named
@RequestScoped
public class LoginHandler extends BaseAuthenticator implements Authenticator {

    private static final Logger logger = Logger.getLogger(LoginHandler.class.getName());
    @Inject
    private MailSession mailSession;
    @Inject
    private Credentials credentials;
    @Inject
    private FacesContext context;

    public LoginHandler() {
    }

    public LoginHandler(MailSession mailSession, Credentials credentials, FacesContext context) {
        this.mailSession = mailSession;
        this.credentials = credentials;
        this.context = context;
    }

    @Override
    public void authenticate() {
        AuthenticationStatus status = AuthenticationStatus.FAILURE;
        try {
            String username = credentials.getUsername();
            if (notEmpty(username) && mailSession.authenticate(username)) {
                logger.info("User logged in : " + mailSession.getUser());
                status = AuthenticationStatus.SUCCESS;
                setUser(new UserImpl(username));
            } else {
                context.addMessage(null, new FacesMessage("Invalid user : " + username));
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
        }
        setStatus(status);
    }

    private boolean notEmpty(String username) {
        return username != null && !username.isEmpty();
    }
}
